package textconvert;

import java.io.UnsupportedEncodingException;

/**
 * 
 * @author Bing
 * @version 1.1
 *
 */
public class ConstByteArray {
	private byte[] buffer;
	private int size;
	private int offset;
	
	public ConstByteArray(){
		this(null,0,0);
	}
	
	public ConstByteArray(ConstByteArray b){
		this(b.buffer, b.offset, b.size);
	}

	public ConstByteArray(byte[] refBuf, int offset, int len){
		this.buffer = refBuf;
		this.offset = offset;
		this.size = len;
	}
	
	public void reset(byte[] refBuf, int offset, int len){
		this.buffer = refBuf;
		this.offset = offset;
		this.size = len;
	}

	public final void resetSize(int offset, int size){
		this.offset = offset;
		this.size = size<0?0:size;
	}
	
	public final void resetSize(int size){		
		this.size = size<0?0:size;
	}
	
	public final byte byteAt(int i){
		return buffer[offset + i];
	}

	public final int length(){
		return size;
	}

	public String toString(String enc) throws UnsupportedEncodingException{   
		return new String(buffer, offset, size, enc);
	}

	public final byte[] getByte(int offset, int len){
		byte[] buf = new byte[len];
		System.arraycopy(buffer, this.offset + offset, buf, 0, len);
		return buf;
	}
	
	public final ConstByteArray getSubArray(int offset, int len){
		return new ConstByteArray(this.buffer, offset, len);
	}
	
	public final boolean regionMatches(byte[] arr, int pos, int len){		
		if(len>this.size)
			return false;

		for(int i=0; i<len; i++){
			if(this.buffer[i + this.offset] != arr[pos + i])
				return false;
		}
		return true;
	}
	
	public final boolean regionMatches(ConstByteArray arr, int pos, int len){
		return regionMatches(arr.buffer, arr.offset + pos, len);
	}
	
	public final int indexOf(byte[] arr, int fromIndex){
		int len = arr.length;
		boolean match = true;
		int iCount = this.size - len;
		for(int i=fromIndex; i<iCount; i++){
			for(int j=0; j<len; j++){
				if(this.buffer[this.offset + i + j] != arr[j]){
					match = false;
					break;
				}					
			}
			if(match){
				return i;
			}
		}
		return -1;
	}

	public boolean equals(Object obj) {
		if(this==obj)
			return true;
		if(obj instanceof ConstByteArray){
			ConstByteArray barr = (ConstByteArray)obj;
			return regionMatches(barr.buffer, barr.offset, barr.size);
		}
		return false;
	}
	
	
}

